package com.syedu.day14;

import com.google.common.collect.Lists;
import com.syedu.day13.Car;

import java.util.*;

/**
 * description：Map的分类数据操作
 * @author Administrator
 * @date 2022/3/29 13:48
 */
public class MapDemo2 {
    public static void main(String[] args) {
        Car car1 = new Car("Benz", "E300L", 400000.0);
        Car car2 = new Car("Bmw", "320Li", 250000.0);
        Car car3 = new Car("Audi", "Q7", 700000.0);
        Car car4 = new Car("Byd", "汉EV", 250000.0);
        Car car5 = new Car("Benz", "C200L", 250000.0);
        Car car6 = new Car("Audi", "A4L", 300000.0);
        Car car7 = new Car("Bmw", "M3", 800000.0);
        Car car8 = new Car("Benz", "EQS", 1500000.0);
        Car car9 = new Car("Audi", "e-tron", 700000.0);
        Car car10 = new Car("Audi", "R8", 2300000.0);
        List<Car> carList = Lists.newArrayList(car1, car2, car3, car4, car5, car6, car7, car8, car9, car10);

        Map<String, List<Car>> mapCars = categoryCars(carList);

        //遍历
        Set<Map.Entry<String, List<Car>>> entries = mapCars.entrySet();
        Iterator<Map.Entry<String, List<Car>>> iterator = entries.iterator();
        while(iterator.hasNext()){
            Map.Entry<String, List<Car>> entry = iterator.next();
            String key = entry.getKey();
            List<Car> value = entry.getValue();
            System.out.println(key);
            value.forEach(System.out::println);
        }
    }

    /**
     * 把List集合转换成Map集合,以品牌来分类存储数据
     */
    public static Map<String, List<Car>> categoryCars(List<Car> carList) {
        Map<String, List<Car>> mapCars = null;
        if (carList != null && carList.size() > 0) {
            mapCars = new HashMap<>();
            //循环List集合,得到每一个汽车对象
            for (Car car : carList) {
                //判断Map集合中是否包含当前汽车的品牌
                if(mapCars.containsKey(car.getBrand())){
                    //map中存在该品牌的汽车
                    mapCars.get(car.getBrand()).add(car);
                }else{
                    //map中不存在该品牌的汽车
                    List<Car> subList = new ArrayList<>();
                    subList.add(car);
                    mapCars.put(car.getBrand(),subList);
                }
            }
        }
        return mapCars;
    }
}